package qlsl.androiddesign.api.aspect;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.support.v4.content.ContextCompat;

import com.cx.annotation.aspect.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

import io.reactivex.functions.Consumer;
import qlsl.androiddesign.api.manager.ActivityManager;
import qlsl.androiddesign.api.util.commonutil.DialogUtil;
import qlsl.androiddesign.api.util.commonutil.Log;
import qlsl.androiddesign.api.util.commonutil.TDevice;


/**
 * 类描述：申请系统权限切片，根据注解值申请所需运行权限
 * 需要传入的键：****
 * 传入的值类型：****
 * 传入的值含义：****
 * 是否必传：****
 * 作者：郑朝军 on 2017/6/14 11:29
 * 邮箱：1250393285@qq.com
 * 公司：武汉智博创享科技有限公司
 * 修改人：郑朝军 on 2017/6/14 11:29
 * 修改备注：
 */
@Aspect
public class SysPermissionAspect
{
    @Around("execution(@com.cx.annotation.aspect.Permission * *(..)) && @annotation(permission)")
    public void aroundJoinPoint(final ProceedingJoinPoint joinPoint, final Permission permission)
            throws Throwable
    {
        final String[] permissions = permission.value();
        final Activity activity = ActivityManager.getInstance().currentActivity();
        if (!checkPermissions(activity, permissions))
        {
            RxPermissions rxPermissions = new RxPermissions(activity);
            rxPermissions.setLogging(Log.isDebug);
            rxPermissions.requestEach(permissions).subscribe(new Consumer<com.tbruyelle
                    .rxpermissions2.Permission>()
            {
                @Override
                public void accept(com.tbruyelle.rxpermissions2.Permission permission) throws
                        Exception
                {
                    if (permission.granted)
                    {// 用户已经同意该权限
                        if (permissions[permissions.length - 1].equals(permission
                                .name))
                        {
                            try
                            {
                                joinPoint.proceed();//获得权限，执行原方法
                            }
                            catch (Throwable throwable)
                            {
                                throwable.printStackTrace();
                            }
                        }
                    }
                    else if (permission.shouldShowRequestPermissionRationale)
                    {// 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                        DialogUtil.showTipsDialog(activity);
                    }
                    else
                    {// 用户拒绝了该权限，并且选中『不再询问』
                        DialogUtil.showTipsDialog(activity);
                    }
                }
            });
        }
        else
        {
            try
            {
                joinPoint.proceed();//获得权限，执行原方法
            }
            catch (Throwable throwable)
            {
                throwable.printStackTrace();
            }
        }
    }

    /**
     * 检查是否有该权限
     *
     * @param context
     * @param permissions
     * @return
     */
    private boolean checkPermissions(Context context, String... permissions)
    {
        if (TDevice.CURRENT_SYSTEM_VERSION)
        {
            for (String permission : permissions)
            {
                if (ContextCompat.checkSelfPermission(context, permission) == PackageManager
                        .PERMISSION_DENIED)
                {
                    return false;
                }
            }
        }
        return true;
    }
}


